#include "pg_common.h"

CONNECTION_DB init_db(char * conf){

  CONNECTION_DB connection = malloc(sizeof(struct pgconn_t));
  connection->conf = (CONF_DB)load_conf(conf);

  if (connection->conf !=NULL){
    
    char string_conn[256];

    sprintf(string_conn, "%s %s %s %s %s", connection->conf->host,
            connection->conf->port, connection->conf->dbname,
            connection->conf->user, connection->conf->password);

    connection->pgconn = PQconnectdb(string_conn);
    if (PQstatus(connection->pgconn)!=CONNECTION_OK){
      printf("erro - %s", PQerrorMessage(connection->pgconn));
      connection=NULL;
    }
  }
  else
    connection =  NULL;
  return connection;
}

void free_db(CONNECTION_DB connection){
  if (connection->conf!=NULL){
    SYSLOG("FINISN CONF");
    free(connection->conf->host);
    free(connection->conf->port);
    free(connection->conf->dbname);
    free(connection->conf->user);
    free(connection->conf->password);
    free(connection->conf);
  }
  if (connection->pgconn !=NULL){
    SYSLOG("PQFINIS");
    PQfinish(connection->pgconn);
  }
  SYSLOG("FINIS CONNEC");
  free(connection);
}
/*----------------------------------------------------
le arquivo de configuracao do DB
-----------------------------------------------------*/
CONF_DB load_conf(char * config){
  CONF_DB conf = malloc (sizeof (struct conf_t));
  FILE * f = fopen(config, "r");
  if (f!=NULL){
    char * buffer = malloc(sizeof(char)*256);
    conf->host = get_next_line(f,buffer);
    conf->port = get_next_line(f,buffer);
    conf->dbname = get_next_line(f,buffer);
    conf->user =  get_next_line(f,buffer);
    conf->password = get_next_line(f,buffer);
  }
  return conf;
}


char * get_next_line(FILE * f, char * buffer){
  buffer = fgets(buffer, 255, f);
  char * aux = malloc(sizeof(char)*strlen(buffer));
  strcpy(aux,buffer);
  remove_enter(aux);
  return aux;
}

void remove_enter(char * buffer){
  while (*buffer!='\n' && *buffer!='\0')
    buffer++;
  *buffer='\0';
}
